import 'dart:typed_data';

import '../../library.dart';
import '../enum/control_error_type.dart';

abstract class ControlResponseBase {
  // 错误码
  ControlErrorType? errorType;

  // 是否成功
  bool get isSuccess => errorType == ControlErrorType.success;
}

// 查询强制固件升级响应
class ForceUpgradeReadResponse extends ControlResponseBase {
  // 强制固件升级状态
  FirmwareForceUpgradeStatus forceUpgradeStatus =
      FirmwareForceUpgradeStatus.unknown;

  // 目标的最低版本号
  int targetLowVersion = 0;

  // 目标的最高版本号
  int targetHighVersion = 0;

  ForceUpgradeReadResponse.fromBytes(Uint8List bytes) {
    if (bytes.length < 9) {
      throw Exception('$runtimeType 数据长度不足');
    }
    ByteData byteData = bytes.buffer.asByteData();
    // 强制固件升级状态
    forceUpgradeStatus =
        FirmwareForceUpgradeStatus.getTypeByNum(byteData.getUint8(0)) ??
            FirmwareForceUpgradeStatus.unknown;
    // 目标的最低版本号
    targetLowVersion = byteData.getUint32(1, Endian.little);
    // 目标的最高版本号
    targetHighVersion = byteData.getUint32(5, Endian.little);
    // 设置错误码
    if (forceUpgradeStatus != FirmwareForceUpgradeStatus.unknown) {
      errorType = ControlErrorType.success;
    }
  }
}

// 写强制固件升级响应
class ForceUpgradeWriteResponse extends ControlResponseBase {
  // 强制固件升级状态
  FirmwareForceUpgradeStatus forceUpgradeStatus =
      FirmwareForceUpgradeStatus.unknown;

  // 目标的最低版本号
  int targetLowVersion = 0;

  // 目标的最高版本号
  int targetHighVersion = 0;

  ForceUpgradeWriteResponse.fromBytes(Uint8List bytes) {
    if (bytes.length < 9) {
      throw Exception('$runtimeType 数据长度不足');
    }
    ByteData byteData = bytes.buffer.asByteData();
    // 强制固件升级状态
    forceUpgradeStatus =
        FirmwareForceUpgradeStatus.getTypeByNum(byteData.getUint8(0)) ??
            FirmwareForceUpgradeStatus.unknown;
    // 错误码
    errorType = ControlErrorType.getTypeByNum(byteData.getUint8(1));
    if (errorType != ControlErrorType.success) {
      throw Exception('${errorType?.name}');
    }
    // 目标的最低版本号
    targetLowVersion = byteData.getUint32(2, Endian.little);
    // 目标的最高版本号
    targetHighVersion = byteData.getUint32(6, Endian.little);
  }
}
